package utils.webdav;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import java.net.URI;

public class WebDavInitUtil {
    public static HttpClient initHttpClient() {

        PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager();
        //设置最大连接数
        pcm.setMaxTotal(100);
        pcm.setDefaultMaxPerRoute(80);
        // 通过连接池获取 httpClient 对象
        return HttpClients.custom().setConnectionManager(pcm).build();
    }

    public static HttpClientContext initContext() {
        WebDavConfig config = WebDavConfig.getInstance();
        URI uri = null;
        try {
            uri = new URI(config.getBaseURL());
        } catch (Exception ignored) {
        }
        // uri 转换成 HttpHost 对象
        HttpHost target = null;
        if (uri != null) {
            target = new HttpHost(uri.getHost(), uri.getPort());
        }

        // 用户名/密码认证
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(config.getUserName(), config.getPassWord());
        if (target != null) {
            credentialsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), credentials);
        }

        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicScheme = new BasicScheme();
        authCache.put(target, basicScheme);

        // Add AuthCache to the execution context
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credentialsProvider);
        context.setAuthCache(authCache);

        return context;
    }
}
